import React, { Component } from "react";
import { render } from "react-dom";
import SortableTree, { changeNodeAtPath, addNodeUnderParent, removeNodeAtPath } from "react-sortable-tree";
// import request from 'superagent';
import { restRequest as request } from '../../lib';
import { Modal } from "antd";
import FamilyMemberDetailForm from "../Forms/FamilyMemberDetailForm";
import { connect } from 'dva';

@connect()
export default class FamilyTree extends Component {
  constructor(props) {
    super(props);

    this.state = {
      visible: false,
      treeData: []
    };

    this.loadMembersFromServer = () => {
      var self = this;
      request({
        method: 'GET',
        url: 'members/descendant/1',
        success_fn: (res) => {
          if(res){
            self.setState({treeData: res})
          }
        },
        failure_fn: (err, errorResp) => {
          console.debug('error',err, errorResp);
        }
      })
    }

    this.handleCanDrop = (param) => {
      // debugger
    }
    this.handleGetNodeKey = (param) => {
      // debugger
    }
  }

  showModal = (e) => {      
    let self = this;
    let id = e.target.getAttribute('id');
    let title = "成员详细信息 (" + e.target.getAttribute('title') + ")";
    request({
      method: 'GET',
      url: 'members/detail/'+id+'?withChild=false',
      query: { withChild: false },
      success_fn: (res) => {
        if(res){
          self.setState({
            visible: true,
            id: id,
            title: title,
            memberData: res,
          });
        }
      },
      failure_fn: (err, errorResp) => {
        console.debug('error',err, errorResp);
      }
    })
  }

  handleOk = (e) => {
    this.setState({
      visible: false,
    });
  }

  handleCancel = (e) => {
    this.setState({
      visible: false,
    });
  }

  handleCreate = () => {
    const form = this.formRef.props.form;
    form.validateFields((err, values) => {
      if (err) {
        return;
      }
      values.id = this.state.id;
      this.props.dispatch({
        type: 'form/submitRegularForm',
        payload: values,
      });
      form.resetFields();
      this.setState({ visible: false });
    });
  }

  saveFormRef = (formRef) => {
    this.formRef = formRef;
  }

  componentDidMount() {
    this.loadMembersFromServer();
  }
  
  render() {
    const getNodeKey = ({ treeIndex }) => treeIndex;
    return (
      <div style={{ height: 5000 }}>
        <SortableTree
          treeData={this.state.treeData}
          onChange={treeData => this.setState({ treeData })}
          // canDrag={true}
          // canDrop={param => this.handleCanDrop({param})}
          generateNodeProps={({ node, path }) => ({
            title: [
              <input name={node.id}
                style={{ fontSize: '1.1rem' }}
                value={node.title}
                placeholder="成员姓名"
                onChange={event => {
                  const title = event.target.value;

                  this.setState(state => ({
                    treeData: changeNodeAtPath({
                      treeData: state.treeData,
                      path,
                      getNodeKey,
                      newNode: { ...node, title },
                    }),
                  }));
                }}
                onKeyPress={event => {
                    var self = event.target;
                    if (event.key === 'Enter') {
                      self.blur();
                    }
                  }
                }    
                onBlur={event => {
                    request({
                      method: 'POST',
                      url: 'primary',
                      data: { title: node.title, id: node.id },
                      accept: 'application/json',
                      success_fn: (res) => {
                        // self.blur();
                      },
                      failure_fn: (err, errorResp) => {
                        console.debug('error',err, errorResp);
                      }
                    })
                  }
                }
              />,
              <button
                id={node.id}
                title={node.title}
                onClick={this.showModal}
              >
                详细
              </button>,
              <span> - </span>,
              <input name={node.sid}
                style={{ fontSize: '1.1rem' }}
                value={node.stitle}
                placeholder="配偶姓名"
                onChange={event => {
                  const stitle = event.target.value;

                  this.setState(state => ({
                    treeData: changeNodeAtPath({
                      treeData: state.treeData,
                      path,
                      getNodeKey,
                      newNode: { ...node, stitle },
                    }),
                  }));
                }}
                onKeyPress={event => {
                    var self = event.target;
                    if (event.key === 'Enter') {
                      self.blur();
                    }
                  }
                }    
                onBlur={event => {
                    request({
                      method: 'POST',
                      url: 'spouse',
                      data: { stitle: node.stitle, sid: node.sid },
                      accept: 'application/json',
                      success_fn: (res) => {
                        // self.blur();
                      },
                      failure_fn: (err, errorResp) => {
                        console.debug('error',err, errorResp);
                      }
                    })
                  }
                }
              />,
              <button
                id={node.sid}
                title={node.stitle}
                onClick={this.showModal}
              >
                详细
              </button>,
              ],            
            buttons: [
              <button
                onClick={() =>{
                  var self = this;
                  request({
                    method: 'POST',
                    url: 'members',
                    data: { parentId: node.id },
                    accept: 'application/json',
                    success_fn: (res) => {
                      self.setState(state => ({
                        treeData: addNodeUnderParent({
                          treeData: state.treeData,
                          parentKey: path[path.length - 1],
                          expandParent: true,
                          getNodeKey,
                          newNode: {
                            id: res.id,
                            sid: res.sid,
                            title: '',
                            stitle: '',
                          },
                        }).treeData,
                      }))
                    },
                    failure_fn: (err, errorResp) => {
                      console.debug('error',err, errorResp);
                    }
                  })
                }
              }
              >
                增加子孙
              </button>,
              <button
                onClick={() =>{
                  var self = this;
                  request({
                    method: 'DELETE',
                    url: 'members/'+node.id,
                    accept: 'application/json',
                    success_fn: (res) => {
                      self.setState(state => ({
                        treeData: removeNodeAtPath({
                          treeData: state.treeData,
                          path,
                          getNodeKey,
                          }),
                        }))
                    },
                    failure_fn: (err, errorResp) => {
                      console.debug('error',err, errorResp);
                    }
                  })                  
                  }
                }
              >
                删除
              </button>,
              // <button
              //   id={node.id}
              //   title={node.title}
              //   onClick={this.showModal}
              // >
              //   详细
              // </button>,
            ],
          })}          
        />
          <FamilyMemberDetailForm
            title={this.state.title}
            id={this.state.id}
            memberData={this.state.memberData}
            wrappedComponentRef={this.saveFormRef}
            visible={this.state.visible}
            onCancel={this.handleCancel}
            onCreate={this.handleCreate}
          />
      </div>
    );
  }
}